// pages/detail/detail.js
const app = getApp();

Page({
  data: {
    post: {},
    comments: [],
    commentText: "",
  },

  onLoad(options) {
    const postId = options.id;
    this.loadPostDetail(postId);
    this.loadComments(postId);
  },

  // 加载帖子详情
  loadPostDetail(postId) {
    // 模拟数据
    const mockPost = {
      id: postId,
      user: {
        name: "小明",
        avatar: "/images/avatar1.png",
      },
      content:
        "今天带我家小猫咪去公园玩，它特别开心！看到其他小动物也很兴奋，一直在跑来跑去。这是它第一次来公园，表现得很勇敢呢！",
      images: ["/images/cat1.jpg", "/images/cat2.jpg", "/images/cat3.jpg"],
      likes: 128,
      comments: 32,
      time: "2小时前",
      isLiked: false,
    };

    this.setData({ post: mockPost });
  },

  // 加载评论
  loadComments(postId) {
    // 模拟评论数据
    const mockComments = [
      {
        id: 1,
        user: { name: "小红", avatar: "/images/avatar2.png" },
        content: "好可爱的小猫咪！",
        time: "1小时前",
      },
      {
        id: 2,
        user: { name: "小李", avatar: "/images/avatar3.png" },
        content: "看起来玩得很开心呢",
        time: "30分钟前",
      },
    ];

    this.setData({ comments: mockComments });
  },

  // 点赞/取消点赞
  toggleLike() {
    const post = this.data.post;
    post.isLiked = !post.isLiked;
    post.likes += post.isLiked ? 1 : -1;

    this.setData({ post });

    wx.showToast({
      title: post.isLiked ? "已点赞" : "已取消",
      icon: "success",
    });
  },

  // 显示评论
  showComments() {
    // 滚动到评论区域
    wx.pageScrollTo({
      selector: ".comments-section",
      duration: 300,
    });
  },

  // 分享帖子
  sharePost() {
    wx.showShareMenu({
      withShareTicket: true,
      menus: ["shareAppMessage", "shareTimeline"],
    });
  },

  // 预览图片
  previewImage(e) {
    const current = e.currentTarget.dataset.url;
    wx.previewImage({
      current,
      urls: this.data.post.images,
    });
  },

  // 评论输入
  onCommentInput(e) {
    this.setData({
      commentText: e.detail.value,
    });
  },

  // 提交评论
  submitComment() {
    if (!this.data.commentText.trim()) {
      wx.showToast({
        title: "请输入评论内容",
        icon: "none",
      });
      return;
    }

    const newComment = {
      id: this.data.comments.length + 1,
      user: { name: "我", avatar: "/images/my-avatar.png" },
      content: this.data.commentText,
      time: "刚刚",
    };

    this.setData({
      comments: [newComment, ...this.data.comments],
      commentText: "",
    });

    wx.showToast({
      title: "评论成功",
      icon: "success",
    });
  },

  onShareAppMessage() {
    return {
      title: this.data.post.content,
      path: `/pages/detail/detail?id=${this.data.post.id}`,
    };
  },
});
